import { Inject, Injectable } from '@nestjs/common';
import { and, eq, gte } from 'drizzle-orm';
import { MySql2Database } from 'drizzle-orm/mysql2';
import { dateUtils } from 'my-ts-core';

import { DRIZZLE_CONNECTION } from '@database/constants/database.constants';
import { userActiveToken } from '@database/schema';

import { UserActiveToken } from '../models/user-active-token.model';

@Injectable()
export class UserActiveTokensRepository {
  constructor(
    @Inject(DRIZZLE_CONNECTION)
    private readonly db: MySql2Database,
  ) {}

  async query(): Promise<UserActiveToken[]> {
    const query = await this.db
      .select({
        username: userActiveToken.username,
        deviceId: userActiveToken.deviceId,
        accessToken: userActiveToken.accessToken,
      })
      .from(userActiveToken)
      .where(
        and(
          gte(userActiveToken.dateExpired, dateUtils.getCurrentDate()),
          eq(userActiveToken.enabled, 1),
        ),
      );

    return query.map((p) => ({
      username: p.username,
      deviceId: p.deviceId,
      accessToken: p.accessToken,
    }));
  }
}
